package org.example.backend.demos.web.UserModule.service.impl;


import org.example.backend.demos.web.UserModule.dao.AuthDao;
import org.example.backend.demos.web.UserModule.dao.UserDao;
import org.example.backend.demos.web.UserModule.entity.LoginDTO;
import org.example.backend.demos.web.UserModule.entity.LoginResult;
import org.example.backend.demos.web.UserModule.entity.User;
import org.example.backend.demos.web.UserModule.entity.UserDTO;
import org.example.backend.demos.web.UserModule.service.UserService;
import org.example.backend.demos.web.Util.JwtTokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    @Autowired
    private AuthDao authDao;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional
    public User register(UserDTO userDTO) {
        // 检查用户名是否已存在
        if (usernameExists(userDTO.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查手机号是否已存在
        if (phoneExists(userDTO.getPhone())) {
            throw new RuntimeException("手机号已存在");
        }

        User user = new User();
        BeanUtils.copyProperties(userDTO, user);

        // 加密密码
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));


        user.setId(null);
        user.setRole(userDTO.getRole());
        user.setCreateTime(LocalDateTime.now().format(formatter));
        user.setToken(null);
        userDao.insert(user);
        return user;
    }

    @Override
    public LoginResult login(LoginDTO loginDTO) {
        // 根据用户名查询用户
        User user = userDao.selectByUsername(loginDTO.getUsername());
//        if (user == null) {
//            throw new RuntimeException("用户名或密码错误");
//        }

        // 验证角色
//        if ("admin".equals(loginDTO.getLoginType()) && !"admin".equals(user.getRole())) {
//            throw new RuntimeException("非管理员账号");
//        }

//        if ("auth".equals(loginDTO.getLoginType()) && !"auth".equals(user.getRole())) {
//            throw new RuntimeException("非志愿者账号");
//        }
//        String password = passwordEncoder.encode(loginDTO.getPassword());
        String password = loginDTO.getPassword();
        String username = loginDTO.getUsername();
        UsernamePasswordAuthenticationToken authenticationToken = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
        try {
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            if (authenticate.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(authenticate);
                LoginResult principal = (LoginResult) authenticate.getPrincipal();
                Object object = authenticate.getPrincipal();
                System.out.println(object);
                String token = jwtTokenUtil.generateToken(principal.getId(), principal.getUsername(), principal.getRole());
                int inserttoken = authDao.updateUsername(principal.getUsername(), token);
                return new LoginResult(principal.getId(), principal.getUsername(),"", principal.getRole(), token);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new LoginResult();


    }

    @Override
    public User findByUsername(String username) {
        return userDao.selectByUsername(username);
    }

    @Override
    public boolean usernameExists(String username) {
        return userDao.existsByUsername(username);
    }

    @Override
    public boolean phoneExists(String phone) {
        return userDao.existsByPhone(phone);
    }



}